"""
Alpha101因子库基础使用示例
========================

展示如何使用Alpha101因子库进行因子计算。
"""

import numpy as np
import sys
import os

# 添加项目根目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))

def example_basic_usage():
    """基础使用示例"""
    print("=" * 60)
    print("Alpha101因子库基础使用示例")
    print("=" * 60)
    
    try:
        # 1. 导入必要的模块
        from factor.data.interface import DataInterface
        from factor.alpha101.core import Alpha101Factory
        from factor.engine.calculator import FactorCalculator
        
        print("✓ 成功导入所有模块")
        
        # 2. 创建数据接口和示例数据
        print("\n步骤1: 创建示例数据")
        data_interface = DataInterface()
        
        # 创建100只股票，252个交易日的示例数据
        sample_data = data_interface.create_sample_data(
            n_stocks=100, 
            n_days=252, 
            seed=42
        )
        
        print(f"✓ 创建了 {sample_data['close'].shape[0]} 只股票，{sample_data['close'].shape[1]} 个交易日的数据")
        print(f"✓ 数据字段: {list(sample_data.keys())}")
        
        # 3. 查看数据信息
        data_info = data_interface.get_data_info(sample_data)
        print(f"✓ 数据大小: {data_info['memory_usage_mb']:.2f} MB")
        
        # 4. 创建Alpha101工厂
        print("\n步骤2: 创建Alpha101因子工厂")
        factory = Alpha101Factory(use_numba=False)  # 暂时不使用numba
        
        # 列出可用因子
        available_factors = factory.list_available_factors()
        print(f"✓ 可用因子数量: {len(available_factors)}")
        print(f"✓ 前5个因子: {available_factors[:5]}")
        
        # 5. 查看因子信息
        print("\n步骤3: 查看因子信息")
        alpha001_info = factory.get_factor_info('alpha001')
        print(f"✓ Alpha001描述: {alpha001_info['description']}")
        print(f"✓ Alpha001依赖: {alpha001_info['dependencies']}")
        print(f"✓ Alpha001窗口: {alpha001_info['window']}")
        
        # 6. 创建计算器
        print("\n步骤4: 创建因子计算器")
        calculator = FactorCalculator(use_numba=False, max_workers=2)
        
        # 7. 尝试计算因子（注意：大部分因子还未实现）
        print("\n步骤5: 尝试计算因子")
        
        # 由于大部分因子还未实现，我们展示如何处理这种情况
        try:
            result = calculator.compute_single_factor('alpha001', sample_data)
            if 'error' in result:
                print(f"✓ Alpha001计算遇到预期错误: {result['error']}")
            else:
                print(f"✓ Alpha001计算成功！")
                print(f"  - 计算时间: {result['computation_time']:.4f} 秒")
                print(f"  - 结果形状: {result['factor_values'].shape}")
        except Exception as e:
            print(f"✓ Alpha001尚未完全实现: {str(e)}")
        
        # 8. 批量计算多个因子
        print("\n步骤6: 批量计算示例")
        factor_list = ['alpha001', 'alpha002', 'alpha003']
        
        batch_results = calculator.compute_multiple_factors(
            factor_list, 
            sample_data, 
            parallel=False
        )
        
        print(f"✓ 批量计算完成，处理了 {len(batch_results)} 个因子")
        
        for factor_id, result in batch_results.items():
            if 'error' in result:
                print(f"  - {factor_id}: 错误 - {result['error']}")
            else:
                print(f"  - {factor_id}: 成功")
        
        # 9. 获取计算统计
        print("\n步骤7: 计算统计信息")
        stats = calculator.get_computation_stats()
        print(f"✓ 总计算次数: {stats['total_calculations']}")
        print(f"✓ 平均计算时间: {stats['average_time']:.4f} 秒")
        
        cache_info = calculator.get_cache_info()
        print(f"✓ 缓存命中率: {cache_info['hit_ratio']:.2%}")
        
        print("\n" + "=" * 60)
        print("🎉 基础使用示例完成！")
        print("=" * 60)
        
        return True
        
    except Exception as e:
        print(f"\n❌ 示例执行失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def example_data_preprocessing():
    """数据预处理示例"""
    print("\n" + "=" * 60)
    print("数据预处理示例")
    print("=" * 60)
    
    try:
        from factor.data.interface import DataInterface
        from factor.data.validator import DataValidator
        from factor.data.preprocessor import DataPreprocessor
        
        # 创建示例数据
        data_interface = DataInterface()
        sample_data = data_interface.create_sample_data(n_stocks=50, n_days=100)
        
        # 人为添加一些问题数据
        problem_data = sample_data.copy()
        
        # 添加缺失值
        problem_data['close'][10:15, 20:25] = np.nan
        
        # 添加异常值
        problem_data['volume'][5, 30] = problem_data['volume'][5, 30] * 1000
        
        print("✓ 创建了包含问题的示例数据")
        
        # 数据验证
        validator = DataValidator()
        validation_report = validator.validate_all(problem_data)
        
        print(f"✓ 数据验证完成")
        print(f"  - 验证结果: {'通过' if validation_report['is_valid'] else '失败'}")
        print(f"  - 警告数量: {len(validation_report['warnings'])}")
        
        if validation_report['warnings']:
            print("  - 主要警告:")
            for warning in validation_report['warnings'][:3]:
                print(f"    * {warning}")
        
        # 数据预处理
        preprocessor = DataPreprocessor()
        processed_data = preprocessor.preprocess_all(problem_data)
        
        print(f"✓ 数据预处理完成")
        
        # 生成预处理报告
        preprocessing_report = preprocessor.get_preprocessing_report(problem_data, processed_data)
        
        print(f"✓ 预处理报告:")
        print(f"  - 新增字段: {preprocessing_report['summary']['added_fields']}")
        
        for field, changes in preprocessing_report['field_changes'].items():
            if changes['missing_filled'] > 0:
                print(f"  - {field}: 填充了 {changes['missing_filled']} 个缺失值")
        
        print("\n🎉 数据预处理示例完成！")
        
        return True
        
    except Exception as e:
        print(f"\n❌ 数据预处理示例失败: {str(e)}")
        return False

def example_performance_benchmark():
    """性能基准测试示例"""
    print("\n" + "=" * 60)
    print("性能基准测试示例")
    print("=" * 60)
    
    try:
        from factor.engine.calculator import FactorCalculator
        from factor.data.interface import DataInterface
        
        # 创建不同规模的数据进行测试
        data_interface = DataInterface()
        calculator = FactorCalculator(use_numba=False)
        
        test_sizes = [
            (50, 100),   # 小规模
            (100, 252),  # 中规模
            (200, 500),  # 大规模
        ]
        
        print("✓ 开始性能基准测试")
        
        for n_stocks, n_days in test_sizes:
            print(f"\n测试规模: {n_stocks} 股票 × {n_days} 交易日")
            
            # 创建测试数据
            test_data = data_interface.create_sample_data(n_stocks, n_days)
            data_size_mb = sum(arr.nbytes for arr in test_data.values()) / (1024 * 1024)
            
            print(f"  数据大小: {data_size_mb:.2f} MB")
            
            # 基准测试（虽然因子还未实现，但可以测试框架性能）
            try:
                benchmark_result = calculator.benchmark_factor('alpha001', test_data, n_runs=3)
                
                if 'error' not in benchmark_result:
                    print(f"  平均计算时间: {benchmark_result['mean_time']:.4f} 秒")
                    print(f"  吞吐量: {benchmark_result['throughput_per_second']:.2f} 次/秒")
                else:
                    print(f"  基准测试遇到预期错误（因子未实现）")
                    
            except Exception as e:
                print(f"  基准测试遇到预期错误: {str(e)}")
        
        print("\n🎉 性能基准测试示例完成！")
        
        return True
        
    except Exception as e:
        print(f"\n❌ 性能基准测试示例失败: {str(e)}")
        return False

def main():
    """主函数"""
    print("Alpha101因子库使用示例")
    print("作者: X-Quant Team")
    print("版本: 0.1.0")
    
    # 运行所有示例
    examples = [
        example_basic_usage,
        example_data_preprocessing,
        example_performance_benchmark
    ]
    
    success_count = 0
    for example in examples:
        try:
            if example():
                success_count += 1
        except Exception as e:
            print(f"示例执行异常: {str(e)}")
    
    print(f"\n总结: {success_count}/{len(examples)} 个示例成功运行")
    
    if success_count == len(examples):
        print("\n🎉 所有示例都成功运行！Alpha101因子库基础架构工作正常。")
        print("\n下一步:")
        print("1. 实现更多Alpha101因子的具体计算逻辑")
        print("2. 添加Numba加速支持")
        print("3. 完善测试用例")
        print("4. 优化性能")
    else:
        print("\n⚠️ 部分示例运行失败，请检查相关模块。")

if __name__ == "__main__":
    main()